package com.example.alarmdemo;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;


import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.TimeoutException;

import butterknife.BindView;

public class RabbitMqUtils {
    private static Connection connection;
    private static Channel channel;
    static Runnable runnable;
    private static Context context;
    private static Handler mHandler;
    static AlarmUtils alarmUtils = new AlarmUtils();
    static ArrayList<AlarmInfo> list = new ArrayList<>();
    static AlarmAdapter adapter;
    static AlertDialog dialog;

    public static ConnectionFactory setUpConnectionFactory() {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.IpHost);//主机地址：
        factory.setPort(Constants.Port);// 端口号
        factory.setUsername(Constants.Username);// 用户名
        factory.setPassword(Constants.password);// 密码

        factory.setAutomaticRecoveryEnabled(true);// 设置连接恢复
        factory.setRequestedHeartbeat(5);
        factory.setNetworkRecoveryInterval(2000);
        return factory;

    }

    static Thread subscribe() {

        final ConnectionFactory factory = setUpConnectionFactory();
        Thread subThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 创建新的连接
                    connection = factory.newConnection();
                    // 创建通道
                    channel = connection.createChannel();
                    // 处理完一个消息，再接收下一个消息
                    channel.basicQos(1);
                    // 随机命名一个队列名称
                    String queueName = System.currentTimeMillis() + "queueName";
                    // 声明交换机类型
                    channel.exchangeDeclare(Constants.MQ_EXCHANGE_CAR, "topic", true);
                    Log.i("topic", "run: " + Constants.MQ_EXCHANGE_CAR);
                    // 声明队列（持久的、非独占的、连接断开后队列会自动删除）
                    AMQP.Queue.DeclareOk q = channel.queueDeclare(queueName, false, false, true, null);// 声明共享队列
                    // 根据路由键将队列绑定到交换机上（需要知道交换机名称和路由键名称）
                    //创建消费者
                    channel.queueBind(q.getQueue(), Constants.MQ_EXCHANGE_CAR, Constants.routingKey);
                    Consumer consumer = new DefaultConsumer(channel) {
                        @Override
                        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                            super.handleDelivery(consumerTag, envelope, properties, body);
                            String msg = new String(body);
                            if (msg != null) {

                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        addData(msg);
                                        alarmUtils.set(RabbitMqUtils.context,mHandler,list);
                                        alarmUtils.speech();
                                        if (dialog == null || !dialog.isShowing()) {
                                            Dialogshow();
                                            alarmUtils.flashLight();//灯带闪烁
                                            runnable = alarmUtils.flash();//屏幕闪烁
                                            alarmUtils.playSongs();
                                        } else {
                                            adapter.notifyDataSetChanged();
                                        }


                                    }
                                });

                            }

                            Log.i("topic", "run: " + msg);
                        }

                    };
                    channel.basicConsume(q.getQueue(), true, consumer);


                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e("IOException", "run: " + e.toString());
                } catch (TimeoutException e) {
                    e.printStackTrace();
                    Log.e("TimeoutException", "run: " + e.toString());
                }
            }

        });

        return subThread;
    }


    private static void Dialogshow() {

        View view = View.inflate(context, R.layout.mydialog, null);
        RecyclerView recyclerView = view.findViewById(R.id.rlist);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new AlarmAdapter(list);
        recyclerView.setAdapter(adapter);
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
        alertDialogBuilder.setView(view);
        alertDialogBuilder.setTitle("警报！！！");
        dialog = alertDialogBuilder.create();
        dialog.setCanceledOnTouchOutside(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            dialog.getWindow().setType((WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY));
        } else {
            dialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
        }


        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                list.clear();
                //处理监听事件
                alarmUtils.closeLight(mHandler, runnable, RabbitMqUtils.context);
                alarmUtils.closeSongs();
                alarmUtils.closeLight();
                alarmUtils.closeSpeech();
            }
        });
        dialog.show();
    }

    public static void addData(String messageData) {
        Collections.reverse(list);
        AlarmInfo alarmInfo = new AlarmInfo();
        alarmInfo.setMessage(messageData);
        list.add(alarmInfo);
        Collections.reverse(list);
    }

    public static void set(Handler Handler, Context mcontext) {
        mHandler = Handler;
        context = mcontext;
    }

    public static void closeCoon(Thread thread) {

        Thread closeThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (connection != null && connection.isOpen())
                        connection.close();
                    if (channel != null && channel.isOpen())
                        channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
        });
        closeThread.start();
        closeThread.interrupt();
        if (thread != null) thread.interrupt();
    }
}

